//
//  NetworkHelper.swift
//  NetworkHelper
//
//  Created by 远成物流 on 2017/6/27.
//
//

import AFNetworking

enum RequestType : Int{
    case GET = 0
    case POST = 1
}

class NetworkHelper: AFHTTPSessionManager {
    static let shareInstance : NetworkHelper = {
        
        let helper = NetworkHelper()
        helper.responseSerializer.acceptableContentTypes?.insert("text/html")
        return helper
    }()
}

extension NetworkHelper{
    func request(method:RequestType , urlString:String , parameters:[String:Any] , finished:@escaping (_ result:AnyObject? , _ error:AnyObject?) -> ()) {
        
        // 1.定义成功的回调闭包
        let successCallBack = { (task : URLSessionDataTask, result : Any?) -> Void in
            finished(result as AnyObject?, nil)
        }
        
        // 2.定义失败的回调闭包
        let failureCallBack = { (task : URLSessionDataTask?, error : Error) -> Void in
            finished(nil, error as AnyObject?)
        }
        
        // 3.发送网络请求
        if method == .GET {
            
            get(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
            
        } else {
            
            post(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
        
    }
}
